package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class ColorChooser extends JComponent{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Color selectedColor = Color.black;;
	
	public ColorChooser(){
		
		this.setPreferredSize(new Dimension(20,20));
		
		addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				Color selected = JColorChooser.showDialog(
						ColorChooser.this, "Selecione a cor", selectedColor);
				
				if(selected != null){
					selectedColor = selected;
					repaint();
					fireActionListener();
				}
			}
		});
		
	}
	
	public Color getSelectedColor() {
		return selectedColor;
	}

	public void setSelectedColor(Color selectedColor) {
		this.selectedColor = selectedColor;
	}

	public void addActionListener(ActionListener listener){
		this.listenerList.add(ActionListener.class, listener);
	}
	
	private void fireActionListener(){
		
		ActionEvent evt = new ActionEvent(this, ActionEvent.RESERVED_ID_MAX+1, "new color");
		
		for(ActionListener l : this.listenerList.getListeners(ActionListener.class)){
			l.actionPerformed(evt);
		}
	}
	
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		g.setColor(selectedColor);
		
		g.fillRect(0, 0, this.getWidth(), this.getHeight());
	}
	
	public static void main(String args[]){

		JFrame frm = new JFrame("Teste");
		
		ColorChooser sc = new ColorChooser();
		
		frm.add(sc);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setSize(500,500);
		frm.setVisible(true);
		
	}
}
